import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { HttpException, ParameterException, Success } from '@/core/HttpException'
import {
  addInsert,
  getFieldValues,
  getFields,
  commandTotal,
  getPaginationStr,
  getOrderBy,
  createWhere,
  addUpdate,
  getUpdateContent,
} from '@/common/utils/sql'
import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/news/add'
import commonDel from '@/api/v1/common/single-table/del'
import { valueSetListBySetCode } from '@/api/v1/system/value-set/listBySetCode'
import { getValueName } from '@/common/utils/array'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v3/news`,
})
router.post('/add', verifyToken, validator(schema, 'body'), async (ctx: Models.Ctx) => {
  // 先判断文章内容的类型
  const params: any = ctx.request.body
  const { fileId, ...realParams } = params
  let fieldObj = {
    ...realParams,
  }
  fieldObj.status = 0
  let result = (
    await command(
      addInsert(`INSERT INTO v3_news
 (${getFields(fieldObj)})
  values
   (${getFieldValues(fieldObj)}
   );`),
      true,
    )
  ).results
  if (result.affectedRows !== 1) {
    throw new HttpException()
  }
  const newsId = result.insertId
  result = (await command(`SELECT id FROM v3_cos WHERE file_id = '${fileId}'`, true)).results
  if (result?.length !== 1) {
    throw new HttpException()
  }
  fieldObj = {
    newsId,
    attachmentFileId: result[0].id,
  }
  result = (
    await command(
      addInsert(
        `INSERT INTO v3_news_attachment
 (${getFields(fieldObj)})
  values
   (${getFieldValues(fieldObj)}
   );`,
        null,
        null,
      ),
      true,
    )
  ).results
  if (result.affectedRows !== 1) {
    throw new HttpException()
  }

  throw new Success({ data: null, msg: '测试' })
})
router.post('/list', verifyToken, async (ctx: Models.Ctx) => {
  const { results: valueSetResults } = await valueSetListBySetCode({ setCodes: ['V3_NEWS_TYPE'] })
  const {
    title,
    status,
    isPagination = true,
    pageSize = 20,
    offset = 0,
    orderField,
    orderDirection,
    onlyTotal = false,
  } = ctx.request.body as any
  /**
   * 关键字必须用大写字母
   */
  let where = createWhere(
    [
      {
        field: 'title',
        value: title,
        type: 'like',
      },
      {
        field: 'status',
        value: status,
      },
    ],
    {
      defAlias: 'n',
    },
  )
  let total = 0
  let paginationStr = ''
  if (isPagination) {
    total = await commandTotal({ tableName: 'v3_news', where })
    if (!onlyTotal) {
      paginationStr = getPaginationStr({ pageSize, offset })
    }
  }
  let list: any = []
  if (!onlyTotal) {
    // 根据orderField 和 orderDirection 进行排序
    const orderBy = getOrderBy({ orderField, orderDirection })
    list = (
      await command(
        `SELECT n.id, title, summary, cover_image, na.attachment_file_id, publish_date, view_count, created_at, status, updated_at, author, type FROM v3_news n 
left join v3_news_attachment na on n.id = na.news_id ${where} ${orderBy} ${paginationStr};`,
        true,
      )
    ).results
  }
  list = list.map((item) => {
    return {
      ...item,
      // 如果 valueSetResults 中只有唯一一个值集，则第三个参数可以省略
      typeName: getValueName(valueSetResults, item.type),
    }
  })
  throw new Success({
    data: list,
    total,
  })
})
router.post('/update', verifyToken, async (ctx: Models.Ctx) => {
  const params: any = ctx.request.body
  const { id, ...fieldObj } = params
  if (!id) {
    throw new ParameterException()
  }
  const result = (
    await command(
      addUpdate(`UPDATE v3_news SET ${getUpdateContent(fieldObj)} WHERE id = '${id}'
 ;`),
      true,
    )
  ).results
  if (result.affectedRows === 1) {
    throw new Success({ data: result, msg: '修改成功' })
  }
})
router.post(
  '/del',
  verifyToken,
  commonDel({
    tableName: 'v3_news',
  }),
)
router.post('/get', verifyToken, async (ctx: Models.Ctx) => {
  const params: any = ctx.request.body
  const { id } = params
  if (!id) {
    throw new ParameterException()
  }
  const result = (
    await command(
      addUpdate(`SELECT n.*, na.attachment_file_id FROM v3_news n INNER JOIN v3_news_attachment na on na.new_id = n.id WHERE n.id = '${id}'
 ;`),
      true,
    )
  ).results
  if (result.affectedRows === 1) {
    throw new Success({ data: result, msg: '修改成功' })
  }
})
export default router
